package com.example.administrator.im.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.example.administrator.im.MyApplication;
import com.example.administrator.im.config.ImageConfig;
import com.example.administrator.im.data.IMData;
import com.example.administrator.im.db.ContactInvitedDBHelper;
import com.example.administrator.im.db.FriendDBHelper;
import com.example.administrator.im.db.GroupDBHelper;
import com.example.administrator.im.db.ReceivedInvitationDBHelper;
import com.example.administrator.im.db.UserDBHelper;
import com.example.administrator.im.json.GroupJson;
import com.example.administrator.im.json.ReceivedInvitationJson;
import com.example.administrator.im.json.ResultJson;
import com.example.administrator.im.json.SearchFriendJson;
import com.example.administrator.im.json.Token;
import com.example.administrator.im.json.UserJson;
import com.example.administrator.im.ui.activity.ChatRoomActivity;
import com.example.administrator.im.ui.activity.ChatSettingActivity;
import com.example.administrator.im.ui.activity.HomeActivity;
import com.example.administrator.im.ui.activity.LoginActivity;
import com.example.administrator.im.ui.activity.RegisterActivity;
import com.example.administrator.im.ui.activity.SystemNotifycationActivity;
import com.example.administrator.im.ui.fragment.IMFragment;
import com.example.administrator.im.ui.fragment.LinkmanFragment;
import com.google.gson.Gson;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMContactListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMImageMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.exceptions.HyphenateException;

import org.greenrobot.eventbus.EventBus;
import org.litepal.LitePal;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * create:2018/9/25 20:13
 * author: 姚鸿杰
 **/
public class EMUtils {

    private static final String TAG = "EMUtils";

    private static String getContent(String content) {
        return content == null ? "" : content;
    }

    private static String reason = null;

    private static final int FAIL = -1;
    private static final int LOGIN = 1;
    private static final int LOGIN_USER = 0;

    private static final int GROUPS = 2;
    private static final int RECEIVED = 3;
    private static final int REGISTER = 4;
    private static final int UPDATE_PASSWORD = 5;
    private static final int ADD_LINKMAN = 6;
    private static final int ADD_FRIEND = 7;
    private static final int EDIT_IMG_PATH = 8;

    private static Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            DialogUtils.clearAlerDialog();
            String content = msg.obj.toString();
            int what = msg.what;
            Gson gson = null;
            ResultJson json = null;
            if (what != FAIL) {
                gson = new Gson();
                json = gson.fromJson(content, ResultJson.class);
            }

            switch (what) {
                case LOGIN_USER:
                    if (json.getCode() == HttpUtils.SUCCESS) {
                        UserJson userJson = gson.fromJson(content, UserJson.class);
                        UserDBHelper userWeb = userJson.getData();
                        UserDBHelper user = LitePal.where("username = ?", userWeb.getUsername()).findFirst(UserDBHelper.class);
                        if (!TextUtils.equals(user.getImg_path(), userWeb.getImg_path())) {
                            File file = FileUtils.getFilePath(user.getUsername(), FileUtils.USER_PACK);
                            saveImage(HttpUtils.PORT + userWeb.getImg_path(), file, ImageConfig.getPersonalBig());
                        }
                        user = userWeb;
                        user.save();
                    } else if (json.getCode() == HttpUtils.SUCCESS_NO_CONTENT) {
                        Toast.makeText(MyApplication.getmContext(), json.getData().toString(), Toast.LENGTH_SHORT).show();
                    }
                    break;
                case LOGIN: //登录
                    if (json.getCode() == HttpUtils.SUCCESS) {
                        //本地保存
                        UserJson userJson = gson.fromJson(content, UserJson.class);
                        UserDBHelper user = userJson.getData();
                        user.save();
                    } else if (json.getCode() == HttpUtils.SUCCESS_NO_CONTENT) {
                        Toast.makeText(MyApplication.getmContext(), json.getData().toString(), Toast.LENGTH_SHORT).show();
                    }
                    break;
                case FAIL:    //失败
                    Toast.makeText(MyApplication.getmContext(), content, Toast.LENGTH_SHORT).show();
                    break;
                case GROUPS:    //获取分组
                    if (json.getCode() == HttpUtils.SUCCESS) {
                        GroupJson groupJson = gson.fromJson(content, GroupJson.class);
                        List<GroupDBHelper> grous = groupJson.getData();
                        for (GroupDBHelper group : grous)
                            group.save();

                    } else if (json.getCode() == HttpUtils.SUCCESS_NO_CONTENT) {
                        Toast.makeText(MyApplication.getmContext(), json.getData().toString(), Toast.LENGTH_SHORT).show();
                    }
                    break;
                case RECEIVED:  //收到好友邀请
                    if (json.getCode() == HttpUtils.SUCCESS) {
                        //本地保存
                        ReceivedInvitationJson receivedJson = gson.fromJson(content, ReceivedInvitationJson.class);
                        ReceivedInvitationDBHelper received = receivedJson.getData();
                        received.save();

                        saveContactInvited(received, reason);
                    } else if (json.getCode() == HttpUtils.SUCCESS_NO_CONTENT) {
                        //待用toast提示
                        Log.e(TAG, json.getData().toString());
                    }
                    break;
                case ADD_LINKMAN:   //添加联系人
                    if (json.getCode() == HttpUtils.SUCCESS) {
                        SearchFriendJson searchFriendJson = gson.fromJson(content, SearchFriendJson.class);

                        FriendDBHelper friend_exist = LitePal.where("username = ?", searchFriendJson.getData().getUsername()).findFirst(FriendDBHelper.class);
                        if (friend_exist != null) {
                            return;
                        }

                        FriendDBHelper friend = new FriendDBHelper();
                        friend.setUsername(searchFriendJson.getData().getUsername());
                        friend.setNickname(TextUtils.isEmpty(searchFriendJson.getData().getNickname())
                                ? searchFriendJson.getData().getUsername() : searchFriendJson.getData().getNickname());
                        friend.setImg_path(searchFriendJson.getData().getImg_path());
                        int id = LitePal.where("default_group = ?", String.valueOf(1)).findFirst(GroupDBHelper.class).getId();
                        friend.setGroup_id(id);
                        friend.save();
                    } else {
                        Toast.makeText(MyApplication.getmContext(), json.getData().toString(), Toast.LENGTH_SHORT).show();
                    }
                    break;
                case ADD_FRIEND:
                    if (json.getCode() == HttpUtils.SUCCESS) {
                        //弹出通知提示

                    } else {
                        Toast.makeText(MyApplication.getmContext(), json.getData().toString(), Toast.LENGTH_SHORT).show();
                    }
                    break;
                case REGISTER:  //注册
                    if (json.getCode() == HttpUtils.SUCCESS) {
                        //数据保存到本地数据库
                        UserDBHelper user = new UserDBHelper();
                        user.setUsername(IM_username);
                        user.setPassword(IM_password);
                        user.setNickname(IM_username);     //注册时昵称用账号显示
                        user.save();
                        //弹出提示框判断是否跳转
                        EventBus.getDefault().post(new RegisterActivity.ShowAlterDialog());
                    }
                    break;
                case UPDATE_PASSWORD:   //更新密码
                    if (json.getCode() == HttpUtils.SUCCESS) {
                        //本地处理
                        UserDBHelper user = new UserDBHelper();
                        user.setPassword(IM_password);
                        user.updateAll("username = ?", IM_username);
                        //关闭等待加载
                        DialogUtils.clearAlerDialog();
                    }
                    break;
                case EDIT_IMG_PATH:

                    break;
            }

        }
    };


    private static Message getMessage(String content, int what) {
        Message msg = new Message();
        msg.what = what;
        msg.obj = content;
        return msg;
    }

    /**
     * 解析消息
     *
     * @param msg 消息
     * @return 返回内容
     */
    public static String getContent(EMMessage msg) {
        String content = "";
        int what = msg.getIntAttribute("type", -1);
        switch (what) {
            case IMAGE:
                if (msg.direct() == EMMessage.Direct.RECEIVE) {
                    content = ((EMImageMessageBody) msg.getBody()).getThumbnailUrl();
                } else {
                    content = ((EMImageMessageBody) msg.getBody()).thumbnailLocalPath();
                }
                break;
            case TEXT:
                content = ((EMTextMessageBody) msg.getBody()).getMessage();
                break;
        }
        return content;
    }


    /**
     * 登录操作
     *
     * @param username 账号
     * @param password 密码
     */
    public static void login(final Context context, final String username, final String password) {

        EMClient.getInstance().login(username, password, new EMCallBack() {//回调
            @Override
            public void onSuccess() {
                Log.e(TAG, "登录聊天服务器成功！");

                //关闭加载
                DialogUtils.clearAlerDialog();

                //两个方法是为了保证进入主页面后本地会话和群组都 load 完毕。
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();

                // 可以在此保存LoginInfo到本地，下次启动APP做自动登录用
                SharedPreferences.Editor editor = context.getSharedPreferences("user", Context.MODE_PRIVATE).edit();
                editor.putString("username", username);
                editor.putString("password", password);
                editor.putBoolean("isLogin", true);
                editor.apply();

                final UserDBHelper user = LitePal.where("username = ?", username).findFirst(UserDBHelper.class);
                //web端获取
                HttpUtils.getUserRequest(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e(TAG, e.getMessage());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if (user == null)
                            handler.sendMessage(getMessage(response.body().string(), LOGIN));
                        else {
                            handler.sendMessage(getMessage(response.body().string(), LOGIN_USER));
                        }
                    }
                });

                //跳转activity
                context.startActivity(new Intent(context, HomeActivity.class));
                Activity activity = (Activity) context;
                activity.finish();

            }

            @Override
            public void onProgress(int progress, String status) {
            }

            @Override
            public void onError(int code, final String message) {
                Log.e(TAG, "登录聊天服务器失败！");
                DialogUtils.clearAlerDialog();
                //202密码错误  204用户不存在
                //登录失败提示
//                handler.sendMessage(getMessage(message + code, FAIL));
                EventBus.getDefault().post(new LoginActivity.LoginErrorHint(code));
            }
        });
    }


    /**
     * 登出
     *
     * @param activity 登出按钮的activity
     */
    public static void logout(final Activity activity) {
        //退出登录异步操作
        EMClient.getInstance().logout(true, new EMCallBack() {

            @Override
            public void onSuccess() {

                DialogUtils.clearAlerDialog();

                activity.startActivity(new Intent(activity, LoginActivity.class));
                activity.finish();

                MyApplication app = MyApplication.getApp();
                app.getLastActivity().finish();

                SharedPreferences spf = activity.getSharedPreferences("user", Context.MODE_PRIVATE);

                //删除所有信息,避免下次登录时混乱
                // LitePal.deleteAll(UserDBHelper.class, "username = ?", spf.getString("username", ""));
                LitePal.deleteAll(FriendDBHelper.class);
                LitePal.deleteAll(ContactInvitedDBHelper.class);
                LitePal.deleteAll(GroupDBHelper.class);
                LitePal.deleteAll(ReceivedInvitationDBHelper.class);

                SharedPreferences.Editor editor = activity.getSharedPreferences("user", Context.MODE_PRIVATE).edit();
                editor.clear();
                editor.apply();
            }

            @Override
            public void onProgress(int progress, String status) {
                //退出加载
            }

            @Override
            public void onError(int code, String message) {
                //退出异常
                DialogUtils.clearAlerDialog();
                handler.sendMessage(getMessage(message, FAIL));
            }
        });
    }

    /**
     * 发送消息
     *
     * @param content 消息内容
     * @param account 接收者账号
     * @return
     */
    public static EMMessage sendMessage(String content, String account) {
        EMMessage msg = EMMessage.createTxtSendMessage(content, account);

        UserDBHelper user = LitePal.where("username = ?", msg.getFrom()).findFirst(UserDBHelper.class);
        Log.e(TAG, msg.getFrom());
        Log.e(TAG, user + "");
        msg.setAttribute("imgUrl", user.getImg_path());        //传递用户的图片路径
        msg.setAttribute("type", TEXT);
        //发送消息
        EMClient.getInstance().chatManager().sendMessage(msg);

        return msg;
    }


    /**
     * 发送图片
     *
     * @param img_path      图片路径
     * @param account       接受者账号
     * @param isCompression 是否压缩
     * @return 消息
     */
    public static EMMessage sendImageMessage(String img_path, String account, boolean isCompression) {

        //imagePath为图片本地路径，false为不发送原图（默认超过100k的图片会压缩后发给对方），需要发送原图传true
        EMMessage msg = EMMessage.createImageSendMessage(img_path, isCompression, account);
        msg.setAttribute("type", IMAGE);
        UserDBHelper user = LitePal.where("username = ?", msg.getFrom()).findFirst(UserDBHelper.class);
        msg.setAttribute("imgUrl", user.getImg_path());        //传递用户的图片路径
        EMClient.getInstance().chatManager().sendMessage(msg);

        return msg;
    }

    public static final int IMAGE = 1;
    public static final int TEXT = 2;

    public static final int UPDATE_IMAGE = 0;
    public static final int UPDATE_NICKNAME = 1;
    public static final int UPDATE_SIGNATURE = 2;

    /**
     * 发送透明消息
     *
     * @param what 0:表示修改图片 1:表示修改昵称
     */
    public static void sendAlphaMessage(int what) {

        List<FriendDBHelper> friends = LitePal.findAll(FriendDBHelper.class);
        for (int i = 0; i < friends.size(); i++) {
            EMMessage cmdMsg = EMMessage.createSendMessage(EMMessage.Type.CMD);
            String content = "";
            UserDBHelper user = LitePal.where("username = ?", cmdMsg.getFrom()).findFirst(UserDBHelper.class);
            cmdMsg.setAttribute("what", what);
            switch (what) {
                case UPDATE_IMAGE:  //修改图片
                    cmdMsg.setAttribute("imgUrl", user.getImg_path());        //传递用户的图片路径
                    content = "修改图片";//action可以自定义
                    break;
                case UPDATE_NICKNAME:   //修改昵称
                    cmdMsg.setAttribute("nickname", user.getNickname());
                    content = "修改昵称";
                    break;
                case UPDATE_SIGNATURE:   //修改个性签名
                    cmdMsg.setAttribute("signature", user.getSignature());
                    content = "修改个性签名";
                    break;
            }

            EMCmdMessageBody cmdBody = new EMCmdMessageBody(content);
            String toUsername = friends.get(i).getUsername();//发送给某个人
            cmdMsg.setTo(toUsername);
            cmdMsg.addBody(cmdBody);
            EMClient.getInstance().chatManager().sendMessage(cmdMsg);
        }
    }


    /**
     * 消息监听
     *
     * @return 返回监听器
     */
    public static EMMessageListener getMsgListener() {

        EMMessageListener mMsglistener = new EMMessageListener() {
            @Override
            public void onMessageReceived(final List<EMMessage> messages) { //必须在主线程中操作
                //收到消息
                Log.e(TAG, "接到消息");

                SharedPreferences spf = MyApplication.getmContext().getSharedPreferences("user", Context.MODE_PRIVATE);
                boolean show_content = spf.getBoolean("show_content", true);    //是否有打开来消息通知了显示
                boolean led = show_content && spf.getBoolean("led", true);  //led灯指示
                boolean shock = spf.getBoolean("shock", true);  //震动是否打开

                MyApplication app = MyApplication.getApp();
                EMMessage emmsg = messages.get(0);

                //获取消息是否免打扰
                FriendDBHelper friend = LitePal.where("username = ?", emmsg.getFrom()).findFirst(FriendDBHelper.class);
                boolean disturb = friend.isDisturb();

                if (app.getCountIsZero()) {   //判断应用是否处于后台
                    //处于后台  接收消息逻辑为处理
                    Log.e(TAG, "后台接收消息");

                    if (show_content && !disturb) {
                        NotificationUtils.sendNotification(emmsg, NotificationUtils.CHAT_CHANNEID, true, shock, led);
                    } else {
                        if (shock) {
                            NotificationUtils.setMedia(MyApplication.getmContext(), 500, "prompt _tone.mp3");
                        }
                    }

                    //IM界面会话更新
                    EventBus.getDefault().post(new IMFragment.UpdateConversations(emmsg, false));
                    EventBus.getDefault().post(new HomeActivity.UpdateIsAckedCount());

                    if (app.getmActivity() instanceof ChatRoomActivity) {
                        EventBus.getDefault().post(new ChatRoomActivity.AddMsg(emmsg));
                    }

                    return;
                }

                //app前台处理
                Activity activity = app.getmActivity();
                if (activity instanceof HomeActivity) {
                    Log.e(TAG, "HomeActivity前台");

                    //IM界面会话更新
                    EventBus.getDefault().post(new IMFragment.UpdateConversations(emmsg, false));
                    EventBus.getDefault().post(new HomeActivity.UpdateIsAckedCount());

                    if (disturb) {    //免打扰则直接返回
                        return;
                    }

                    //无通知，但是有铃声响起
                    if (shock)
                        NotificationUtils.setMedia(MyApplication.getmContext(), 500, "prompt _tone.mp3");
                    else
                        NotificationUtils.setMedia(MyApplication.getmContext(), 0, "prompt _tone.mp3");
                } else if (activity instanceof ChatRoomActivity) {
                    Log.e(TAG, "ChatRoomActivity前台");
                    //无通知，添加消息
                    EventBus.getDefault().post(new ChatRoomActivity.AddMsg(emmsg));

                    // 震动
                    if (shock && !disturb)
                        NotificationUtils.setMedia(MyApplication.getmContext(), 500, null);

                    //判断前一个Activity是否为HomeActivity，是就更新数据
                    Activity lastActivity = app.getLastActivity();
                    if (lastActivity instanceof HomeActivity) {
                        EventBus.getDefault().post(new IMFragment.UpdateConversations(messages.get(0),
                                isAcked(EMClient.getInstance().chatManager().
                                        getConversation(emmsg.getUserName())) == 0));
                    }

                } else {
                    Log.e(TAG, "其他页面");

                    //IM界面会话更新
                    EventBus.getDefault().post(new IMFragment.UpdateConversations(emmsg, false));
                    EventBus.getDefault().post(new HomeActivity.UpdateIsAckedCount());

                    if (activity instanceof ChatSettingActivity) {    //聊天设置界面
                        EventBus.getDefault().post(new ChatRoomActivity.AddMsg(emmsg));
                    }

                    //有浮动通知，也有铃声
                    if (show_content && !disturb)
                        NotificationUtils.sendNotification(messages.get(0), NotificationUtils.CHAT_CHANNEID, true, shock, led);
                }
            }

            @Override
            public void onCmdMessageReceived(List<EMMessage> messages) {
                //收到透传消息

                //更新头像UI
                EMMessage emmsg = messages.get(0);
                int what = emmsg.getIntAttribute("what", -1);
                FriendDBHelper friend = LitePal.where("username = ?", emmsg.getUserName()).findFirst(FriendDBHelper.class);
                switch (what) {
                    case UPDATE_IMAGE:
                        String img_path = emmsg.getStringAttribute("imgUrl", "");
                        //判断头像是否与数据库头像地址一致，不一致则修改
                        if (!TextUtils.equals(friend.getImg_path(), img_path)) {
                            friend.setImg_path(img_path);
                            friend.save();
                            EventBus.getDefault().post(new IMFragment.UpdateIMItem());


                            File file = FileUtils.getFilePath(emmsg.getUserName(), FileUtils.FRIEND_PACK);
                            saveImage(HttpUtils.PORT + img_path, file, ImageConfig.getItemSmall());
                        }
                        break;
                    case UPDATE_NICKNAME:
                        String nickname = emmsg.getStringAttribute("nickname", "");
                        if (!TextUtils.equals(friend.getNickname(), nickname)) {
                            friend.setNickname(nickname);
                            friend.save();
                            EventBus.getDefault().post(new IMFragment.UpdateIMItem());
                        }
                        break;
                    case UPDATE_SIGNATURE:
                        String signature = emmsg.getStringAttribute("signature", "");
                        if (!TextUtils.equals(friend.getSignature(), signature)) {
                            friend.setSignature(signature);
                            friend.save();
                        }
                        break;
                }
            }

            @Override
            public void onMessageRead(List<EMMessage> messages) {
                //收到已读回执
            }

            @Override
            public void onMessageDelivered(List<EMMessage> message) {
                //收到已送达回执
            }

            @Override
            public void onMessageRecalled(List<EMMessage> messages) {
                //消息被撤回
            }

            @Override
            public void onMessageChanged(EMMessage message, Object change) {
                //消息状态变动
            }
        };
        return mMsglistener;
    }

    private static void saveImage(String url, final File file, int size) {
        DownloadImageUtils downloadImage = new DownloadImageUtils(url, MyApplication.getmContext(),
                size, size, file, new DownloadImageUtils.ImagedownLoadCallBack() {
            @Override
            public void onDownLoadSuccess(final File file) {
            }

            @Override
            public void onDownLoadFailed() {
            }
        });
        new Thread(downloadImage).start();
    }

    private static List<IMData> imDataList;
    private static int isAckedCount = 0;

    /**
     * @return 返回未读总数
     */
    public static int getisAckedCount() {
        //获取所有会话
        Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();
        if (conversations.size() != 0) {
            List<IMData> msgList = new ArrayList<>();
            isAckedCount = 0;   //先将未读总数标记为0
            for (EMConversation conversation : conversations.values()) {
                int count = isAcked(conversation);
                isAckedCount += count;
                msgList.add(new IMData(conversation.getLastMessage(), count == 0));
            }
            Collections.sort(msgList);  //让其按时间顺序排序
            imDataList = msgList;
        } else {
            imDataList = new ArrayList<>();
        }
        if (isAckedCount > 99)
            isAckedCount = 99;
        return isAckedCount;
    }

    /**
     * @return 返回所有的聊天会话
     */
    public static List<IMData> getConversations() {
        //效率低待修改
        getisAckedCount();
        return imDataList;
    }


    /**
     * 判断该回话中的内容是否以全部读取
     *
     * @param conversation 当前会话
     * @return
     */
    private static int isAcked(EMConversation conversation) {
        int unread = conversation.getUnreadMsgCount();
        return unread;
    }

    /**
     * 设置消息已读
     *
     * @param username 对象账号
     */
    public static void setMsgAcked(String username) {
        EMConversation conversation = EMClient.getInstance().chatManager().getConversation(username);
        if (conversation != null)
            conversation.markAllMessagesAsRead();
    }


    /**
     * 获取count条聊天记录
     *
     * @param account 对方账号
     * @param count   多少条记录
     * @param isInit  是否为获取初始化消息
     * @return 返回消息集合
     */
    public static List<EMMessage> getChattingRecords(String account, int count, boolean isInit) {
        EMConversation conversation = EMClient.getInstance().chatManager().getConversation(account);
        if (null != conversation) {
            List<EMMessage> messages;
            if (isInit) {
                messages = conversation.loadMoreMsgFromDB("", count);
            } else {
                String msgId = conversation.getLastMessage().getMsgId();
                messages = conversation.loadMoreMsgFromDB(msgId, count);
            }
            return messages;
        }
        return new ArrayList<>();
    }

    /**
     * 移除某个user的会话
     *
     * @param username           对方id
     * @param isDeleteChatRecord 是否删除聊天记录
     */
    public static void removeConversation(String username, boolean isDeleteChatRecord) {
        //删除和某个user会话，如果需要保留聊天记录，传false
        EMClient.getInstance().chatManager().deleteConversation(username, isDeleteChatRecord);

        //删除当前会话的某条聊天记录
//        EMConversation conversation = EMClient.getInstance().chatManager().getConversation(username);
//        conversation.removeMessage(deleteMsg.msgId);
    }


    /**
     * 从服务器获取分组
     */
    public static void getGroups() {
        if (LitePal.findAll(GroupDBHelper.class).size() == 0)
            HttpUtils.getGetGroupsRequest(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
//                    Log.e(TAG, e.getMessage());
                    handler.sendMessage(getMessage(e.getMessage(), FAIL));
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    handler.sendMessage(getMessage(response.body().string(), GROUPS));
                }
            });
    }

    /**
     * 添加好友
     *
     * @param friend 好友id
     */
    public static void addFriend(String friend, String reason) {
        //参数为要添加的好友的username和添加理由
        try {
            EMClient.getInstance().contactManager().addContact(friend, reason);
        } catch (HyphenateException e) {
            e.printStackTrace();
        }
    }

    /**
     * 好友监听
     *
     * @return 返回好友监听
     */
    public static EMContactListener getContactListener() {

        EMContactListener contactListener = new EMContactListener() {

            @Override
            public void onContactInvited(final String username, final String reason_) {
                Log.e(TAG, "收到好友邀请");

                //判断是否以为好友
                if (LitePal.where("username = ?", username).findFirst(FriendDBHelper.class) != null) {
                    return;
                }

                ContactInvitedDBHelper contactInvited = LitePal.
                        where("username = ?", username).findFirst(ContactInvitedDBHelper.class);
                if (contactInvited != null) {
                    if (contactInvited.getResult() != -1) {
                        EventBus.getDefault().post(new LinkmanFragment.ContacInvited());
                        return;
                    }
                }

                ReceivedInvitationDBHelper received = LitePal.where("username = ?",
                        username).findFirst(ReceivedInvitationDBHelper.class);
                if (received == null) {
                    //从服务器上获取数据并保存到本地
                    HttpUtils.getFriendRequest(username, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            handler.sendMessage(getMessage(e.getMessage(), FAIL));
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            reason = reason_;
                            handler.sendMessage(getMessage(response.body().string(), RECEIVED));
                        }
                    });
                    return;
                }
                saveContactInvited(received, reason_);
            }

            @Override
            public void onFriendRequestAccepted(String s) {
                //好友请求被同意
                Log.e(TAG, "好友请求被同意");
                //弹出好友被同意通知
                HttpUtils.addFriendRequest(s, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        handler.sendMessage(getMessage(e.getMessage(), FAIL));
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        handler.sendMessage(getMessage(response.body().string(), ADD_FRIEND));
                    }
                });

            }

            @Override
            public void onFriendRequestDeclined(String s) {
                //好友请求被拒绝
                Log.e(TAG, "好友请求被拒绝");
                //弹出好友被同意通知
            }

            @Override
            public void onContactDeleted(String username) {
                //被删除时回调此方法
                Log.e(TAG, "被删除时回调此方法");
                //暂时没有删除好友功能
            }

            @Override
            public void onContactAdded(String username) {
                //增加了联系人时回调此方法
                Log.e(TAG, "增加了联系人时回调此方法");
                //好友请求被同意时添加联系人在这里统一添加


                HttpUtils.getFriendRequest(username, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        DialogUtils.clearAlerDialog();
                        handler.sendMessage(getMessage(e.getMessage(), FAIL));
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        handler.sendMessage(getMessage(response.body().string(), ADD_LINKMAN));
                    }
                });
            }
        };
        return contactListener;
    }

    /**
     * 保存好友邀请
     *
     * @param received
     * @param reason
     */
    private static void saveContactInvited(ReceivedInvitationDBHelper received, String reason) {
        ContactInvitedDBHelper contactInvited = new ContactInvitedDBHelper();
        contactInvited.setUsername(received.getUsername());
        contactInvited.setNickname(TextUtils.isEmpty(received.getNickname())
                ? received.getUsername() : received.getNickname());
        contactInvited.setReason(reason);
        contactInvited.setTime(System.currentTimeMillis());
        contactInvited.setImg_path(received.getImg_path());
        contactInvited.setResult(0);
        contactInvited.save();

        MyApplication app = MyApplication.getApp();
        if (app.getmActivity() instanceof SystemNotifycationActivity) { //系统通知界面更新
            EventBus.getDefault().post(new SystemNotifycationActivity.UpdateSystemNotifycationItem(contactInvited));
        } else { //联系人界面提示
            EventBus.getDefault().post(new LinkmanFragment.ContacInvited());
        }
    }


    //              IM用户体系集成            ------------------------------------------------------------


    private static final String org_name = "1180180721099205";
    private static final String app_name = "fastarrival";
    private static final String client_id = "YXA6-E2PwIz8Eeie_tc-vIj3JQ";
    private static final String client_secret = "YXA68hPTC9MvBul6yXqsjdNbD0MzWbk";
    private static String token;
    private static String IM_username;
    private static String IM_password;

    //逻辑待修改

    /**
     * 获取 APP 管理员 Token
     */
    public static void getToken(final String key) {

        //添加等待加载

        OkHttpClient client = new OkHttpClient();
        String gson = "{\"grant_type\":\"client_credentials\",\"client_id\":\""
                + client_id + "\",\"client_secret\":\"" + client_secret + "\"}";
        String baseUrl = "https://a1.easemob.com/" + org_name + "/" + app_name + "/token";

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), gson);
        final Request request = new Request.Builder().header("content-type", "application/json").post(requestBody).url(baseUrl).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e(TAG, e.getMessage());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String content = response.body().string();
                Gson gson = new Gson();
                Token tk = gson.fromJson(content, Token.class);
                token = tk.getAccess_token();

                switch (key) {
                    case "registerIM":
                        registerIM(IM_username, IM_password, false);
                        break;
                    case "updatePassword":
                        updatePassword(IM_username, IM_password, false);
                        break;
                }
            }
        });
    }


    /**
     * 注册IM用户
     *
     * @param username 注册的IM账号
     * @param password 密码
     */
    public static void registerIM(final String username, final String password, boolean isHaveTonken) {

        if (isHaveTonken) {
            IM_username = username;
            IM_password = password;
            getToken("registerIM");
            return;
        }

        OkHttpClient client = new OkHttpClient();
        String gson = "{\"username\":\"" + username + "\",\"password\":\"" + password + "\"}";
        String baseUrl = "https://a1.easemob.com/" + org_name + "/" + app_name + "/users";
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), gson);
        final Request request = new Request.Builder()
                .addHeader("Authorization", "Bearer " + token)
                .url(baseUrl)
                .put(requestBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                handler.sendMessage(getMessage(e.getMessage(), FAIL));
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {

                HttpUtils.signupRequest(username, password, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        handler.sendMessage(getMessage(e.getMessage(), FAIL));
                        DialogUtils.clearAlerDialog();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        DialogUtils.clearAlerDialog();
                        handler.sendMessage(getMessage(response.body().string(), REGISTER));
                    }
                });

            }
        });
    }

    /**
     * 更新密码
     *
     * @param username 用户账号
     * @param password 用户新密码
     */
    public static void updatePassword(final String username, final String password, boolean isHaveTonken) {

        if (isHaveTonken) {
            IM_username = username;
            IM_password = password;
            getToken("updatePassword");
            return;
        }

        OkHttpClient client = new OkHttpClient();
        String baseUrl = "https://a1.easemob.com/" + org_name + "/" + app_name + "/users/" + username + "/password";
        String gson = "{\"newpassword\":\"" + password + "\"}";
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), gson);
        String access_token = token;
        Request request = new Request.Builder()
                .addHeader("Authorization", "Bearer " + access_token)
                .url(baseUrl)
                .put(requestBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                //关闭等待加载
                DialogUtils.clearAlerDialog();

                //弹出修改失败
                handler.sendMessage(getMessage(e.getMessage(), FAIL));
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                Log.e(TAG, response.body().string());

                //处理修改密码的数据
                //web端处理
                HttpUtils.updateUserRequest(HttpUtils.UPDATE_PASSWORD, password, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        DialogUtils.clearAlerDialog();
                        handler.sendMessage(getMessage(e.getMessage(), FAIL));
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        DialogUtils.clearAlerDialog();
                        handler.sendMessage(getMessage(response.body().string(), UPDATE_PASSWORD));
                    }
                });

            }
        });

    }

}